package com.nice.controller;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.nice.main.Bootstart;
import com.nice.message.Message;
import com.nice.message.MessageHandler;
import com.nice.service.Service;

public class MessageDispatch implements Service {

	private static Logger log = Logger.getLogger(MessageDispatch.class);
	private static final MessageDispatch INSTANCE = new MessageDispatch();
	private Map<Integer, MessageHandler> conns;
	private MessageDao dao;

	private MessageDispatch() {
		conns = new ConcurrentHashMap<Integer, MessageHandler>();
	}

	public static MessageDispatch getInstance() {
		return INSTANCE;
	}

	public void registerHandler(int clientId, MessageHandler handler) {
		conns.put(clientId, handler);
	}

	public void dispatch(Message msg) {
		send(msg);
	}

	public void send(Message msg) {
		log.info(msg.toString());
		if (msg.type == Message.LOGIN) {
			MessageHandler sender = msg.sender;
			conns.put(msg.from, sender);
			List<Message> msgs = dao.query(msg.from);
			for (Message tmp : msgs) {
				sender.handle(tmp);
			}
			dao.delete(msgs);
			log.info("send office msgs:" + msgs.size());
			return;
		}
		MessageHandler handler = conns.get(msg.to);
		if (handler != null) {
			handler.handle(msg);
		} else {
			dao.save(msg);
			log.info(msg.to + " is  offline:");
		}
	}

	public void remove(int clientId) {
		conns.remove(clientId);
	}

	@Override
	public void start(Bootstart bt) {
		dao = (MessageDao) bt.getService("dao");

	}

	@Override
	public void stop(Bootstart bt) {

	}
}
